//
//  YSChatMessageFrame.m
//  YSEmoticonKeyboard
//
//  Created by MOLBASE on 2017/12/21.
//  Copyright © 2017年 YangShen. All rights reserved.
//

#import "YSChatMessageFrame.h"
#import "YSDecoder.h"
#import "YYText.h"

@implementation YSChatMessageFrame

- (void)setChatMessage:(YSChatMessage *)chatMessage {
    _chatMessage = chatMessage;
    
    CGFloat headW  = 40;
    CGFloat headH  = 40;
    CGFloat margin = 10;
    CGFloat headX = chatMessage.userType == YSUserTypeMe ? YSEmoticonScreenWidth - headW - margin : margin;
    self.headViewFrame = CGRectMake(headX, margin, headW, headH);
    
    CGFloat nameX = chatMessage.userType == YSUserTypeOther ? headW + margin * 2 : margin;
    CGRect nameFranem = CGRectMake(nameX, CGRectGetMinY(self.headViewFrame), YSEmoticonScreenWidth - margin * 3 - headW, 20);
    self.nameLabelFrame = nameFranem;
    
    self.attMessage = [YSDecoder decodeWithPlainString:chatMessage.messageContent font:[UIFont systemFontOfSize:17.0f]];
    
    CGFloat AllMargin = 31;
    CGSize maxsize = CGSizeMake(YSEmoticonScreenWidth - (margin * 4 + headW * 2) - AllMargin, MAXFLOAT);
    
    // 创建文本容器
    YYTextContainer *container = [YYTextContainer new];
    container.size = maxsize;
    container.maximumNumberOfRows = 0;
    // 生成排版结果
    YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:self.attMessage];
    
    CGFloat textW = layout.textBoundingSize.width > maxsize.width ? maxsize.width : layout.textBoundingSize.width;
    CGFloat airX = chatMessage.userType == YSUserTypeMe ? YSEmoticonScreenWidth - margin * 2 - headW - textW - AllMargin : margin * 2 + headW;
    self.airViewFrame = CGRectMake(airX, 35, textW + 31, layout.textBoundingSize.height + 16);
    
    CGFloat contentX = chatMessage.userType == YSUserTypeMe ? YSEmoticonScreenWidth - margin * 2 - headW - textW - 18 : margin * 2 + headW + 20;
    self.messageLabelFrame = CGRectMake(contentX, 43, textW, layout.textBoundingSize.height);
    
    self.cellHeight = CGRectGetMaxY(self.messageLabelFrame) + margin * 2;
}

@end
